package com.task.manage.system.controller;

import com.task.manage.common.annotation.Log;
import com.task.manage.common.core.controller.BaseController;
import com.task.manage.common.core.domain.AjaxResult;
import com.task.manage.common.core.domain.entity.SysUser;
import com.task.manage.common.core.page.TableDataInfo;
import com.task.manage.common.enums.BusinessType;
import com.task.manage.common.utils.ShiroUtils;
import com.task.manage.common.utils.StringUtils;
import com.task.manage.common.utils.poi.ExcelUtil;
import com.task.manage.system.domain.TaskManage;
import com.task.manage.system.domain.req.StatisticsReqBO;
import com.task.manage.system.domain.resp.*;
import com.task.manage.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 任务管理器Controller
 *
 * @author ruoyi
 * @date 2024-05-10
 */
@Controller
@RequestMapping("/system/manage")
public class TaskManageController extends BaseController {
    private String prefix = "system/manage";

    @Autowired
    private ITaskManageService taskManageService;

    @Resource
    private RecoryTaskService recoryTaskService;


    @Resource
    private ISysRoleService roleService;

    @RequiresPermissions("system:manage:view")
    @GetMapping()
    public String manage( ModelMap mmap) {
        StatisticsReqBO statisticsReqBO=new StatisticsReqBO();
        SysUser user = ShiroUtils.getSysUser();
        if(!user.isAdmin()){
            Set<String> roles = roleService.selectRoleKeys(user.getUserId());
            boolean hasCommon = roles.stream().anyMatch(role -> role.equals("common"));
            if(!hasCommon){
                statisticsReqBO.setUserId(user.getUserId());
                statisticsReqBO.setQueryAllFlag("Y");
            }
        }
        StatisticsResp statisticsResp=taskManageService.statisticsData(statisticsReqBO);
        if(statisticsResp!=null){
            mmap.put("totalCount",statisticsResp.getTotalCount());
            mmap.put("totalEvaluate",statisticsResp.getTotalEvaluate());
            mmap.put("totalNotEvaluate",statisticsResp.getTotalNotEvaluate());
            mmap.put("evaluateRate",statisticsResp.getEvaluateRate());
        }
        return prefix + "/manage";
    }

    /**
     * 查询任务管理器列表
     */
    @RequiresPermissions("system:manage:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TaskManageReqBO taskManage) {
        startPage();
        SysUser user = ShiroUtils.getSysUser();
        if(!user.isAdmin()){
            Set<String> roles = roleService.selectRoleKeys(user.getUserId());
            boolean hasCommon = roles.stream().anyMatch(role -> role.equals("common"));
            if(!hasCommon){
                taskManage.setUserId(user.getUserId());
                taskManage.setQueryAllFlag("Y");
            }
        }
        List<TaskManageResp> list=taskManageService.selectMangeInfoList(taskManage);
        return getDataTable(list);
    }

    /**
     * 导出任务管理器列表
     */
    @RequiresPermissions("system:manage:export")
    @Log(title = "任务管理器", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TaskManageReqBO taskManage) {
        List<TaskManageResp> list = taskManageService.selectMangeInfoList(taskManage);
        list.stream().forEach(taskManageResp -> {
            if(taskManageResp.getActualAmount()!=0){
                taskManageResp.setProductActualAmount(taskManageResp.getActualAmount());
            }else{
                taskManageResp.setProductActualAmount(taskManageResp.getProductAmount());
            }
        });
        ExcelUtil<TaskManageResp> util = new ExcelUtil<TaskManageResp>(TaskManageResp.class);
        return util.exportExcel(list, "任务管理器数据");
    }

    /**
     * 新增任务管理器
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存任务管理器
     */
    @RequiresPermissions("system:manage:add")
    @Log(title = "任务管理器", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TaskManage taskManage) {
        return toAjax(taskManageService.insertTaskManage(taskManage));
    }

    /**
     * 修改任务管理器
     */
    @RequiresPermissions("system:manage:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        TaskManage taskManage = taskManageService.selectTaskManageById(id);
        mmap.put("taskManage", taskManage);
        return prefix + "/edit";
    }

    /**
     * 复制任务
     */
    @RequiresPermissions("system:manage:edit")
    @GetMapping("/copyTask/{id}")
    public String copyTask(@PathVariable("id") String ids, ModelMap mmap) {
        logger.info("获取到的参数id:{}",ids);
        List<Long> idsList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        List<TaskManageCopyResp> taskManageCopyRespList=taskManageService.selectCopyInfoList(idsList);
        mmap.put("taskList", taskManageCopyRespList);
        mmap.put("ids", ids);
        return prefix + "/copyTask";
    }

    /**
     * 结算初始化信息
     * @return
     */
    @GetMapping("/settleInit/{id}")
    public String settleInit(@PathVariable("id") String ids,ModelMap mmap){
        logger.info("获取到的参数id:{}",ids);
        List<Long> idsList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        List<TaskManageCopyResp> taskManageCopyRespList=taskManageService.selectCopyInfoList(idsList);
        mmap.put("settleList", taskManageCopyRespList);
        // 计算总价
        double totalAmount = taskManageCopyRespList.stream()
                .mapToDouble(task -> {
                    Double actualAmount = task.getActualAmount();
                    if (actualAmount != null&&actualAmount>0) {
                        return actualAmount;
                    } else {
                        return task.getProductAmount();
                    }
                }) // 获取每个对象的实价或者产品单价
                .sum(); // 对实价或者产品单价求和得到总价
        mmap.put("totalAmount", totalAmount);
        mmap.put("ids",ids);
        return prefix + "/settleInfo";
    };

    /**
     * 复制任务
     * @return
     */
    @RequiresPermissions("system:manage:edit")
    @GetMapping("/settleCopy/{ids}")
    @ResponseBody
    public AjaxResult settleCopy(@PathVariable("ids") String ids){
        logger.info("获取到的参数id:{}",ids);
        List<Long> idsList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        taskManageService.updateBatchTaskCopyManage(idsList);
        return AjaxResult.success();
    };

    /**
     * 结算信息
     * @return
     */
    @RequiresPermissions("system:manage:edit")
    @GetMapping("/settleTask/{ids}")
    @ResponseBody
    public AjaxResult settleTask(@PathVariable("ids") String ids){
        logger.info("获取到的参数id:{}",ids);
        List<Long> idsList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        taskManageService.updateBatchTaskManage(idsList);
        return AjaxResult.success();
    };

    /**
     * 批量出评价
     * @return
     */
    @RequiresPermissions("system:manage:edit")
    @GetMapping("/batchEvaluate/{ids}/{type}")
    @ResponseBody
    public AjaxResult batchEvaluate(@PathVariable("ids") String ids,@PathVariable("type") String type){
        logger.info("获取到的参数id:{}",ids);
        List<Long> idsList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
       taskManageService.updateBatchBatchEvaluate(idsList,type);
        return AjaxResult.success();
    };

    /**
     * 新增任务管理器
     */
    @GetMapping("/personList")
    @RequiresPermissions("require:task")
    public String personList() {
        return prefix + "/person";
    }

    /**
     * 修改保存任务管理器
     */
    @RequiresPermissions("system:manage:edit")
    @Log(title = "任务管理器", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TaskManage taskManage) {
        if(StringUtils.isEmpty(taskManage.getPersonRemark())&&taskManage.getActualAmount()==null){
            return AjaxResult.error("实付价格和人员备注不能都为空");
        }
        return toAjax(taskManageService.updateTaskManage(taskManage));
    }

    /**
     * 删除任务管理器
     */
    @RequiresPermissions("system:manage:remove")
    @Log(title = "任务管理器", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        logger.info("获取到的id是:{}", ids);
        List<Long> idsList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        List<RecoryTaskResp>  taskManageList= taskManageService.selectMangeListByIdList(idsList);
        if(CollectionUtils.isEmpty(taskManageList)){
            //如果没有直接删除任务管理器数据
            taskManageService.deleteTaskManageByIds(ids);
        }else{
            taskManageList.stream().forEach(recoryTaskResp -> {
                recoryTaskService.deleteTask(recoryTaskResp,idsList);
            });
        }
        return AjaxResult.success();
    }

    /**
     * 回收任务
     * @return
     */
    @PostMapping("/recovery")
    @ResponseBody
    public AjaxResult recovery(String ids){
        if (StringUtils.isEmpty(ids)) {
            return error("请选择对应的人员信息");
        }
        logger.info("获取到的id是:{}", ids);
        List<Long> idsList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        List<RecoryTaskResp>  taskManageList= taskManageService.selectMangeListByIdList(idsList);
        if(CollectionUtils.isEmpty(taskManageList)){
             //如果没有可回收的任务 那么应该删除任务管理器数据
              taskManageService.deleteTaskManageByIds(ids);
        }else{
            taskManageList.stream().forEach(recoryTaskResp -> {
                recoryTaskService.recoryTask(recoryTaskResp,idsList);
            });
        }
        return AjaxResult.success("回收任务成功");
    }

}
